package com.lin.fengxiu.service;

import com.lin.fengxiu.bo.OrderMessageBO;
import com.lin.fengxiu.exception.http.ServerErrorException;
import com.lin.fengxiu.model.Order;
import com.lin.fengxiu.repository.OrderRepository;
import com.lin.fengxiu.repository.SkuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @ClassName OrderCancelService
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/4/14 6:28
 * @Version 1.0
 */
@Service
public class OrderCancelService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private SkuRepository skuRepository;

    /**
     * @Description TODO 根据事件name对订单进行取消
     * @param messageBO
     */
    @Transactional
    public void cancel(OrderMessageBO messageBO){
        if(messageBO.getOrderId()<=0){
            throw new ServerErrorException(9999);
        }
//        this.cancel(messageBO.getOrderId());
    }

    /**
     * @Description TODO 根据事件name解析得到的orderId校验该order是否存在
     * @param oid
     */
    private void cancel(Long oid){
        // order 是否为空校验
        Optional<Order> orderOptional = orderRepository.findById(oid);
        if(orderOptional == null){
            return;
        }
        Order order = null;
        try {
            order = orderOptional.orElseThrow(()->{
                throw new ServerErrorException(9999);
            });
        }catch (Throwable e){
            e.printStackTrace();
        }

        // 订单状态更新
        int res = orderRepository.cancelOrder(oid);
        if(res != 1){
            return;
        }
        // 库存归还
        order.getSnapItems().forEach(i->{
           skuRepository.recoverStock(i.getId(),i.getCount().longValue());
        });

    }
}
